package com.edu.demo.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.demo.entity.*;
import com.edu.demo.exception.MyNullPointerException;
import com.edu.demo.exception.UpdateErrorException;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.service.IContractService;
import com.edu.demo.service.IProjectService;
import com.edu.demo.service.ISignService;
import com.edu.demo.utils.SecurityUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 签到表 前端控制器

 * @author jixuewei
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/sign")
public class SignController {


    @Autowired
    private ISignService signService;

    @Autowired
    private IContractService contractService;

    @Autowired
    private IProjectService projectService;


    /**
     * 只能签到当天
     * @return
     */
    @GetMapping("/add")
    @PreAuthorize("@ps.hasPerm('stu:sign:add')")
    public AjaxResult addSign(){
        Sign sign = new Sign();
        Student student = SecurityUtils.getStudent();
        Date date = new Date();
        Sign sign1 = signService.selectByDateAndStuId(student.getId(), date);
        date = new Date();
        int hours = date.getHours();
        if(hours<11)sign.setMorningSignIn(date);
        else if(hours<13)sign.setMorningSignOut(date);
        else if(hours<15)sign.setNoonSignIn(date);
        else sign.setNoonSignOut(date);
        sign.setStuId(student.getId());
        sign.setStuName(student.getName());
        if(Objects.isNull(sign1)){ //今天第一次签到
            sign.setDateTime(date);
            boolean save = signService.save(sign);
            if(save) return AjaxResult.success();
            return AjaxResult.error("签到失败");
        }

        try {
            boolean b = signService.updateSign(sign);
            if(b) return AjaxResult.success();
        } catch (UpdateErrorException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error("服务异常，签到失败");
    }

    /**
     * 查询某个项目date日期这个月的签到情况
     * @param para
     * @return
     */
    @PostMapping("/list/month")
    @PreAuthorize("@ps.hasPerm('common:sign:list')")
    public AjaxResult listMonth(@RequestBody Map<String,Object> para){
        String dateDate = (String) para.get("date");
        Date date = Convert.toDate(dateDate);
        Integer projectId = Integer.valueOf((Integer) para.get("projectId")) ;
        try {
            List<Sign> signs = signService.thisMonth(date, projectId);
            return AjaxResult.success(signs);
        }catch (MyNullPointerException e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 查询某个项目date日期这天的签到情况
     * @param para
     * @return
     */
    @PostMapping("/list/day")
    @PreAuthorize("@ps.hasPerm('common:sign:list')")
    public AjaxResult listDay(@RequestBody Map<String,Object> para){
        String dateDate = (String) para.get("date");
        Date date = Convert.toDate(dateDate);
        Integer projectId = (Integer) para.get("projectId");
        QueryWrapper<Contract> query = new QueryWrapper<>();
        if(projectId!=null) {
            query.eq("project_id", projectId);
        }else{
            Teacher teacher = SecurityUtils.getTeacher();
            List<Project> projects = projectService.list(new QueryWrapper<Project>().eq("t_id", teacher.getId()));
            List<Integer> projectIds = projects.stream().map(Project::getId).collect(Collectors.toList());
            if(!projects.isEmpty())
                query.in("project_id",projectIds);
        }
        List<Contract> contracts = contractService.list(query);
        List<Integer> stuIds = contracts.stream().map(Contract::getStuId).collect(Collectors.toList());
        if(stuIds.isEmpty()) return AjaxResult.error("该项目无签订成员");
        date.setHours(0);
        Date clone = (Date) date.clone();
        clone.setHours(23);
        try {
            QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("date_time",date).le("date_time",clone);
            if(SecurityUtils.getStudent()!=null){
                queryWrapper.eq("stu_id",SecurityUtils.getStudent().getId()); //学生查询自己签到
            }else {
                queryWrapper.in("stu_id",stuIds); //老师查询项目的所有学生签到情况
            }
            List<Sign> signs = signService.list(queryWrapper);

            return AjaxResult.success(signs);
        }catch (MyNullPointerException e){
            return AjaxResult.error(e.getMessage());
        }

    }

}
